package com.rljk.controller.backend;

import com.rljk.common.controller.BaseController;
import com.rljk.common.result.CodeMsg;
import com.rljk.common.result.Result;
import com.rljk.domain.common.PageData;
import com.rljk.redis.RedisService;
import com.rljk.service.UserManager;

import com.rljk.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:   zhang
 * Date:     2018/6/27 11:27
 * Description: 后台用户接口
 */
@RestController
@RequestMapping("/backenduser")
@Slf4j
public class UserController extends BaseController{

    @Resource(name = "userService")
    private UserManager userService;

    @Autowired
    RedisService redisService;

    @Autowired
    private AliSendPhoneUtil aliSendPhoneUtil;

    @RequestMapping(value = "/sendmsgcode")
    @ResponseBody
    public Object sendMsgCode(String PHONE) {
        log.info("发送 手机短信验证码");
        Map<String, Object> map = new HashMap<String, Object>();
        PageData pd = new PageData();
        pd = this.getPageData();
        System.out.println("phone:"+pd.getString("PHONE"));
        String result = "00";
        try {
            if (Tools.checkKey("SENDMSGCODE", pd.getString("FKEY"))) { // 检验请求key值是否合法
                if (AppUtil.checkParam("userLoginPhone", pd)) { // 检查参数
                    String size = redisService.get(Const.ALI_CODE_SIZE+pd.getString("PHONE"));
                    if(Tools.notEmpty(size)){
                        if(Integer.parseInt(size)>=Const.ALI_CODE_SIZE){
                            result = "请不要多次发送";
                            return AppUtil.returnObject(new PageData(), map);
                        }
                    }


                    String redisCode = redisService.get(Const.ALI_CODE+pd.getString("PHONE"));
                    System.out.println("redisCode:"+redisCode);
                    if(Tools.isEmpty(redisCode)){
                        //AliSendPhoneUtil aliSendPhoneUtil = new AliSendPhoneUtil();
                        HashMap<String, Object> alimsg = aliSendPhoneUtil.sendMessage(pd.getString("PHONE"));
                        if(alimsg==null){
                            result = "02";
                            return AppUtil.returnObject(new PageData(), map);
                        }
                        if("2".equals(alimsg.get("Code"))){
                            map.put("pd", "发送失败");
                            return AppUtil.returnObject(new PageData(), map);
                        }
                        String redisCo =redisService.get(Const.ALI_CODE+pd.getString("PHONE"));
                        map.put("CODE",redisCo);
                        return Result.success(map);
                    }else {
                        //result = "请不要重复发送验证码";
                        return Result.error(CodeMsg.SENDMSG_ERROT);
                    }

                } else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        //return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * @Author zhang
     * @Description   后台注册用户
     * @Date 2018/7/18 9:57
     * @Param []
     * @return java.lang.Object
     **/
    @RequestMapping(value="/registeruser")
    public Object registerUser(HttpServletRequest request) {
        log.info("后台注册用户");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("REGISTERUSER", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("registerUser",pd)){

                    String codeinfo = ((String)pd.get("CODEINFO")).toUpperCase();
                    log.info("传过来的验证码======"+codeinfo);

                    Cookie[] cookies = request.getCookies();
                    String name =null;
                    String value = null;
                    for(Cookie cookie : cookies){
                        if(cookie.getName().equals(Const.SESSION_SECURITY_CODE)){
                            name = cookie.getName();
                            log.info("从客户cookie获取的key======"+cookie.getName());
                            value = cookie.getValue();
                            log.info("从客户cookie获取的value======"+value);
                        }
                    }

                   /* Cookie cookie = CookieUtil.get(request, Const.SESSION_SECURITY_CODE);
                    String name = cookie.getValue();
                    log.info("cookie中的name==================="+name);*/
                    if (!name.isEmpty()){
                        //String cookieName = cookie.getValue();
                        //log.info("从客户cookie获取的key======"+cookieName);
                        String cookieValue = redisService.get(value);
                        log.info("从获取的验证码======"+cookieValue);
                        if (cookieValue.equals(codeinfo)){
                            String userId = this.getSnowId();
                            pd.put("USER_ID",userId);
                            String password = (String) pd.get("PASSWORD");
                            String SALT = DateUtil.getdaySFM();
                            String md5Password = MD5.getPassword(password + SALT);
                            pd.put("PASSWORD",md5Password);
                            pd.put("SALT", SALT);

                            userService.save(pd);
                            return Result.success(null);
                        }else {
                            return Result.error(CodeMsg.CODE_ERROR);
                        }
                    }else {
                        return Result.error(CodeMsg.LOGINORREGISTER_ERROR);
                    }

                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * @Author zhang
     * @Description 后台用户登录
     * @Date 2018/7/19 10:06
     * @Param [request]
     * @return java.lang.Object
     **/
    @RequestMapping(value="/loginuser")
    public Object loginUser(HttpServletRequest request) {
        log.info("后台注册用户");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("LOGINRUSER", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("loginUser",pd)){

                    String codeinfo = ((String)pd.get("CODEINFO")).toUpperCase();
                    log.info("传过来的验证码======"+codeinfo);

                    Cookie[] cookies = request.getCookies();
                    /*String cookieName =null;
                    for(Cookie cookie : cookies){
                        if(cookie.getName().equals(Const.SESSION_SECURITY_CODE)){
                            cookieName = cookie.getValue();
                            log.info("从客户cookie获取的key======"+cookieName);
                        }
                    }*/
                    Cookie cookie = CookieUtil.get(request, Const.SESSION_SECURITY_CODE);
                    String cookieName = cookie.getValue();
                    log.info("从客户cookie获取的key======"+cookieName);
                    String cookieValue = redisService.get(cookieName);
                    log.info("从客户cookie获取的验证码======"+cookieValue);
                    if (cookieValue.equals(codeinfo)){

                        PageData userInfo = userService.findByNameOrPassword(pd);
                        if (userInfo == null){
                            return Result.error(CodeMsg.LOGIN_ERROR);
                        }else {
                            String password = (String) pd.get("PASSWORD");
                            String SALT = (String) userInfo.get("SALT");
                            String md5Password = MD5.getPassword(password + SALT);
                            if (!md5Password.equals(userInfo.get("PASSWORD"))){
                                return Result.error(CodeMsg.LOGIN_ERROR);
                            }else {
                                return Result.success(CodeMsg.LOGIN_SUCCESS);
                            }
                        }

                    }else {
                        return Result.error(CodeMsg.CODE_ERROR);
                    }



                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }

    }


    /**
     * @Author zhang
     * @Description 后台查询用户信息
     * @Date 2018/7/12 10:31
     * @Param []
     * @return java.lang.Object
     **/
    @RequestMapping(value="/queryuser")
    public Object queryUser() {
        log.info("后台查询用户信息");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("QUERYUSER", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("queryUser",pd)){
                    PageData userInfo = userService.findById(pd);
                    userInfo.remove("PASSWORD");
                    userInfo.remove("SALT");
                    return Result.success(userInfo);
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }



    @RequestMapping(value="/queryalluser")
    public Object queryAllUser() {
        log.info("后台查询所有用户信息");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("QUERYALLUSER", pd.getString("FKEY"))) {
//                if (AppUtil.checkParam("queryAllUser",pd)){
                    List<PageData> allUser = userService.listAll(pd);
                    map.put("list",allUser);
                    return Result.success(map);
//                }else {
//                    return Result.error(CodeMsg.PARAM_LACK);
//                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }




}
